<?php

namespace app\controllers\supplier;

use app\models\City;
use app\controllers\admin\base\AdminController;
use app\models\user\User;

class CityController extends AdminController
{
    public function actionTree()
    {
        $path = __DIR__ . '/cache/tree.json';

        if (!file_exists($path)) {
            $tree = City::getTree2();
            $tree = json_encode($tree);
            file_put_contents($path, $tree);
        }

        $data = file_get_contents($path);
        $filesize = filesize($path);

        return $this->success([
            'tree' => json_decode($data, true),
            'Bytes' => $filesize,
            'KB' => round($filesize / 1024, 2),
        ]);
    }

    public function actionChecked()
    {
        $user_id = $this->post('user_id');
        $address_id = $this->post('address_id');

        if (!$user_id || !$address_id) {
            return $this->fail('操作错误');
        }

        $user = User::findOne(['id' => $user_id]);
        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 不让重复
        $is = User::find()
            ->where(['!=', 'id', $user_id])
            ->andWhere(['address_up' => $address_id])
            ->one();
        if ($is) {
            return $this->fail('该区域已经被设置了');
        }

        $user->address_up = $address_id;
        if ($user->save()) {
            return $this->success();
        }
    }

    public function actionGet()
    {
        $user_id = $this->post('user_id');
        $user = User::findOne(['id' => $user_id]);

        if ($user) {
            return $this->success(['address_id' => $user->address_up]);
        }
    }
}